package com.loveprogrammer.lowercode.dna.service.impl;

import com.loveprogrammer.lowercode.dna.cache.DnaCacheKey;
import com.loveprogrammer.lowercode.dna.def.Dna;
import com.loveprogrammer.lowercode.dna.party.dna.PartyDnaTool;
import com.loveprogrammer.lowercode.dna.service.DnaCacheService;

import java.util.Map;

/**
 * @ClassName DnaCacheServiceImpl
 * @Description 启动后要先缓存dna数据
 * @Author admin
 * @Date 2024/5/31 10:50
 * @Version 1.0
 */
public class DnaCacheServiceImpl implements DnaCacheService {

    private static Map<DnaCacheKey,Dna> dnaMap;
    private static Map<DnaCacheKey,Dna> chlidrenDnaMap;

    private static Map<String,DnaCacheService> otherCacheKeyService;

    static {
        Dna partyDna = PartyDnaTool.getPartyDna();
        dnaMap.put(new DnaCacheKey(partyDna.getBusinessType(),partyDna.getDnaCode()),partyDna);

        Dna accountDna = PartyDnaTool.getPartyAccountDna();
        dnaMap.put(new DnaCacheKey(accountDna.getBusinessType(),accountDna.getDnaCode()),accountDna);

        Dna usageDna = PartyDnaTool.getAccounUsageDna();
        dnaMap.put(new DnaCacheKey(usageDna.getBusinessType(),usageDna.getDnaCode()),usageDna);
    }

    @Override
    public Dna getDna(String businessType, String dnaCode) {
        if( businessType == null || dnaCode == null )
            throw new RuntimeException("参数不能为空!dna, businessType" + businessType + "dnaCode:" +  dnaCode );

        Dna dna = dnaMap.get(new DnaCacheKey(businessType, dnaCode));
        if(dna != null) {
            return dna;
        }
        dna = chlidrenDnaMap.get(new DnaCacheKey(businessType, dnaCode));
        if(dna != null) {
            return dna;
        }
        for (DnaCacheService cacheService : otherCacheKeyService.values()) {
            dna = cacheService.getDna(businessType,dnaCode);
            if(dna != null) {
                return dna;
            }
        }

        throw new RuntimeException("不存在dna, businessType" + businessType + "dnaCode:" +  dnaCode );
    }

}
